<template>
  <div class="address-list-container">
    <h2 class="title">我的收货地址</h2>
    <el-button type="primary" @click="handleAddAddress">添加地址</el-button>

    <el-table
        :data="addressList"
        border
        style="width: 100%; margin-top: 20px"
        :header-cell-style="{ background: '#f8f9fa', color: '#666' }"
    >
      <el-table-column prop="receiver" label="收货人" align="center" />
      <el-table-column prop="phone" label="电话/手机" align="center" />
      <el-table-column prop="region" label="所在地区" align="center" />
      <el-table-column prop="detail" label="详细地址" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
              size="mini"
              type="primary"
              icon="Edit"
              @click="handleEditAddress(scope.row)"
          >
            修改
          </el-button>
          <el-button
              size="mini"
              type="danger"
              icon="Delete"
              @click="handleDeleteAddress(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="移动设置" align="center">
        <template #default="scope">
          <el-button
              size="mini"
              type="primary"
              @click="handleSetDefault(scope.row)"
              v-if="!scope.row.isDefault"
          >
            设为默认
          </el-button>
          <el-tag
              type="success"
              effect="dark"
              v-else
          >
            默认地址
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/修改地址弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        title="添加/修改收货地址"
        width="600px"
    >
      <el-form
          :model="form"
          :rules="rules"
          ref="addressFormRef"
          label-width="120px"
      >
        <el-form-item label="收货人" prop="receiver">
          <el-input v-model="form.receiver" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="电话/手机" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话/手机号码" />
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <div class="location-input-group">
            <el-cascader
                v-model="form.region"
                :options="regionOptions"
                placeholder="请选择所在地区"
                style="width: 80%"
                :props="{
                  expandTrigger: 'hover',
                  label: 'label',
                  value: 'label',
                  children: 'children'
                }"
            />
            <el-button
                @click="getLocation"
                type="default"
                size="small"
                style="margin-left: 8px; width: 20%"
            >
              <i class="el-icon-location"></i> 定位
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input v-model="form.detail" placeholder="请输入详细地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveAddress">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 定位确认对话框 -->
    <el-dialog
        v-model="locationDialogVisible"
        title="确认定位信息"
        width="400px"
        :before-close="handleDialogClose"
    >
      <div class="location-dialog-content">
        <p>检测到您的位置信息如下：</p>
        <div class="location-info">{{ tempLocationText }}</div>

        <div class="modify-section" v-if="showModifyCascader">
          <p style="margin: 15px 0 5px;">如需修改，请选择：</p>
          <el-cascader
              v-model="tempSelectedLocation"
              :options="regionOptions"
              placeholder="重新选择所在地"
              style="width: 100%"
              :props="{
              expandTrigger: 'hover',
              label: 'label',
              value: 'label',
              children: 'children'
            }"
              @change="handleTempLocationChange"
          ></el-cascader>
        </div>

        <el-checkbox v-model="showModifyCascader" style="margin-top: 10px;">
          不使用当前定位，手动修改
        </el-checkbox>
      </div>
      <template #footer>
        <el-button @click="locationDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmLocation">确认使用</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessageBox, ElMessage, ElForm, ElLoading } from 'element-plus';
import { AuthService } from '../../service/auth';
import axios from 'axios';
import { regionData } from 'element-china-area-data';
import { getCurrentLocation } from '../../service/geolocation';

// 初始化服务和用户ID
const authService = new AuthService();
const userId = ref(authService.getUserId());
const addressFormRef = ref(ElForm);

// 地址列表数据
const addressList = ref([]);

// 地区级联数据
const regionOptions = ref(regionData);

// 表单数据和验证规则
const form = ref({
  id: '',
  receiver: '',
  phone: '',
  region: [],  // 存储地区名称数组，如["北京市", "北京市", "东城区"]
  detail: '',
  postcode: '',
  province: '',
  city: '',
  district: '',
  isDefault: false
});

const rules = reactive({
  receiver: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
});

// 对话框状态
const dialogVisible = ref(false);

// 定位相关状态
const locationDialogVisible = ref(false);
const tempLocationText = ref('');
const tempSelectedLocation = ref([]);
const showModifyCascader = ref(false);

// 获取地址列表
const getAddressList = async () => {
  try {
    const { data } = await axios.get(`/api/user/user-address/list-by-user/${userId.value}`);
    // 拼接省市区为region字段
    const formattedData = data.map(item => ({
      ...item,
      region: `${item.province || ''}/${item.city || ''}/${item.district || ''}`
    }));
    addressList.value = formattedData;
  } catch (error) {
    console.error('获取地址列表失败：', error);
    ElMessage.error('获取地址列表失败，请稍后重试');
  }
};

// 添加地址
const handleAddAddress = () => {
  form.value = {
    id: '',
    receiver: '',
    phone: '',
    region: [],
    detail: '',
    postcode: '',
    province: '',
    city: '',
    district: '',
    isDefault: false
  };
  dialogVisible.value = true;
};

// 编辑地址
const handleEditAddress = (row) => {
  // 拆分region为级联选择器需要的数组
  const regionArray = row.region.split('/');
  form.value = {
    ...row,
    region: regionArray
  };
  dialogVisible.value = true;
};

// 保存地址
const handleSaveAddress = async () => {
  // 表单验证
  await addressFormRef.value.validate();

  try {
    // 拆分地区数组为省、市、区单独字段
    const [province, city, district] = form.value.region;
    const addressData = {
      ...form.value,
      province,
      city,
      district,
      userId: userId.value
    };

    if (form.value.id) {
      // 修改地址
      await axios.put('/api/user/user-address/update', addressData);
      ElMessage.success('地址修改成功');
    } else {
      // 新增地址
      await axios.post('/api/user/user-address/add', addressData);
      ElMessage.success('地址添加成功');
    }

    dialogVisible.value = false;
    getAddressList(); // 重新获取地址列表
  } catch (error) {
    console.error('保存地址失败：', error);
    ElMessage.error('保存地址失败，请稍后重试');
  }
};

// 删除地址
const handleDeleteAddress = async (row) => {
  try {
    await ElMessageBox.confirm(
        '此操作将永久删除该地址，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    await axios.delete(`/api/user/user-address/delete/${row.id}`);
    ElMessage.success('地址删除成功');
    getAddressList(); // 重新获取地址列表
  } catch (error) {
    if (error === 'cancel') return;
    console.error('删除地址失败：', error);
    ElMessage.error('删除地址失败，请稍后重试');
  }
};

// 设置默认地址
const handleSetDefault = async (row) => {
  try {
    await axios.put(`/api/user/user-address/set-all-non-default/${userId.value}`);
    await axios.put(`/api/user/user-address/set-default/${row.id}`);
    ElMessage.success('已设为默认地址');
    getAddressList(); // 重新获取地址列表
  } catch (error) {
    console.error('设置默认地址失败：', error);
    ElMessage.error('设置默认地址失败，请稍后重试');
  }
};

// 获取定位并显示对话框
const getLocation = async () => {
  try {
    const loading = ElLoading.service({
      lock: true,
      text: '正在获取位置信息...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // 获取经纬度
    const position = await getCurrentLocation({
      enableHighAccuracy: true,
      timeout: 10000
    });

    // 转换为地址信息
    const { data } = await axios.get(`/api/user/gaode/coordinate`, {
      params: {
        lat: position.latitude,
        lng: position.longitude
      }
    });

    // 构建地址字符串数组
    const { province, city, district } = data.regeocode.addressComponent;
    const locationArray = [province, city, district].filter(Boolean);
    const locationStr = locationArray.join('/');

    // 初始化对话框数据
    tempLocationText.value = locationStr;
    tempSelectedLocation.value = [...locationArray];
    showModifyCascader.value = false;
    locationDialogVisible.value = true;

    loading.close();
  } catch (error) {
    ElMessage.error('获取定位失败，请手动选择');
    console.error('定位错误:', error);
  }
};

// 确认定位信息
const confirmLocation = () => {
  // 使用临时选择的值更新表单
  form.value.region = [...tempSelectedLocation.value];
  locationDialogVisible.value = false;
  ElMessage.success('地区信息已更新');
};

// 处理临时地址修改
const handleTempLocationChange = (value) => {
  tempLocationText.value = value.join('/');
};

// 关闭定位对话框时重置
const handleDialogClose = () => {
  tempSelectedLocation.value = [];
  tempLocationText.value = '';
  showModifyCascader.value = false;
  locationDialogVisible.value = false;
};

// 组件挂载时获取地址列表
onMounted(() => {
  getAddressList();
});
</script>

<style scoped>
.address-list-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #333;
}

::v-deep .el-dialog__body {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}

::v-deep .el-table {
  border-radius: 4px;
}

::v-deep .el-table th {
  font-weight: 500;
}

/* 定位相关样式 */
.location-input-group {
  display: flex;
  align-items: center;
}

.location-dialog-content {
  line-height: 1.6;
}

.location-info {
  padding: 10px;
  margin: 10px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.modify-section {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #e5e7eb;
}
</style>
